<?php

namespace Utuo;

use Think\Controller;

class ForegroundController extends Controller {
	/**
	 * 每页显示条数
	 *
	 * @var int
	 */
	protected $pageSize = 10;
	
	/**
	 * 合作商id
	 *
	 * @var integer
	 */
	protected $pid = null;
	
	/**
	 * 客户ID
	 *
	 * @var integer
	 */
	protected $cid;
	
	/**
	 * 网站ID
	 *
	 * @var integer 
	 */
	protected $sid;
	
	/**
	 * 某客户的模型id(单模型多主题时)
	 * 
	 * @var unknown
	 */
	protected $id;
	
	/**
	 * 用户id
	 *
	 * @var unknown
	 */
	protected $uid;
	
	/**
	 * 栏目ID
	 *
	 * @var integer
	 */
	protected $catId;
	
	/**
	 * 网站信息
	 *
	 * @var array
	 */
	protected $config = array ();
	
	/**
	 * 网站主题信息
	 *
	 * @var array
	 */
	protected $theme = array ();
	
	/**
	 * 模型名称
	 *
	 * @var unknown
	 */
	protected $modelName = "";
	
	/**
	 * 模型控制器名称
	 *
	 * @var unknown
	 */
	protected $modelControllerName = "";
	
	/**
	 * 页面标题
	 *
	 * @var string
	 */
	private $pageTitle = '';
	
	/**
	 * 微信公众号id
	 * 
	 * @var unknown
	 */
	protected $open_id = 0;
	
	/**
	 * 微信配置 
	 * @var unknown
	 */
	protected $wechatConfig = null;
	
	/**
	 * 微信接口
	 * @var unknown
	 */
	protected $wechatAdvance = null;
	
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
		$this->setWechat();
		$this->getLogin();
		$this->tid = I("get.tid", 0, "intval") or $this->tid = I("post.tid", 0, "intval");
		$this->cid = I('get.sid', 0, 'intval') or $this->cid = I("post.sid", 0, "intval");
		$this->sid = $this->cid;
		/* 支持合作商建站 */
		$this->pid = I('get.pid', 0, 'intval') or $this->pid = I("post.pid", 0, "intval");
		$this->pid or $customer = $this->getCustomer() and $this->pid = $customer['partner'];
		if (!$this->cid and !$this->pid) { // 合作商与用户至少设置一个
			$this->cid = C('DEFAULT_SITE_ID');
			$this->pid = I('pid', 0, 'intval') or $customer = $this->getCustomer() and $this->pid = $customer['partner'];
		}
		$this->assign("pid", $this->pid);
		$this->assign("sid", $this->sid);
		$this->assign('imgShow', getImageUrl('', 'show'));
		$this->assign('imgThumb', getImageUrl('', 'thumb'));
		method_exists($this, '_init') && $this->_init();
		/* 微信配置 */
		$this->wechatConfig = $wechat = M("Wechat")->where('cid=%d', $this->cid)->find();
		try {
		    $this->wechatAdvance = new WechatAdvance($wechat['appid'], $wechat['appsecret']);
		    if ( $this->wechatAdvance->getError() ) {
		        $this->wechatAdvance = null;
		    } 
		} catch (\Exception $e) {}
		/* 主题设置 */
		$modelName = $this->modelName;
		$themeStyle = 'Default';
		$themeTemplate = 'Default';
		if ($modelName) {
			$config = $this->invokeLogicMethod($this->modelName, "getModelConfig", array (
					'cid' => $this->cid,
					'pid' => $this->pid 
			)) or $config = $this->getModelConfig($this->id);
			if ($config['status'] != 1) {
			    headers_sent() or header("Content-type:text/html;charset=utf-8");
				die("网站已关闭");
			}
			$this->tid === 0 and $this->tid = $config['theme'];
			$themeConfig = $this->getThemeConfig($this->tid, $config);
			
			$this->assign('style', $themeConfig);
			$config['url'] = url('Home', $this->modelControllerName ? $this->modelControllerName : $modelName, '', array (
					'sid' => $this->sid 
			));
			$this->config = $config;
			$this->assign("config", $config);
			$this->assign(lcfirst($modelName), $config);
			if (!empty($this->tid)) {
				$theme = M("Theme")->find($this->tid);
				$themeStyle = $theme['style'];
				$themeTemplate = $theme['template'];
			}
		}
		$this->assign('system', M('system')->find());
		C('TMPL_PARSE_STRING.__STYLE__', __ROOT__ . '/Public/Style/' . MODULE_NAME . '/' . $themeStyle);
		
		parent::theme($themeTemplate);
		
		C('TMPL_ACTION_ERROR', './error'); // 默认错误跳转对应的模板文件
		C('TMPL_ACTION_SUCCESS', './success'); // 默认成功跳转对应的模板文件
		                                       
		// 统计PV
		PVReport::report($this->cid);
		
		// 记录日志
// 		\Utuo\UtuoLog::doLogPost("WmflFront", array (
// 				'user' => session("user") 
// 		));
	}
	
	/**
	 * 获得模型控制器名
	 * 
	 * @param unknown $modelName
	 * @return boolean
	 */
	protected function getControllerName($modelName) {
		return $modelName;
	}
	
	/**
	 * 设置页面标题
	 *
	 * @param string $pageTitle
	 */
	public function setPageTitle($pageTitle, $suffix = null) {
		$this->pageTitle = $pageTitle;
		empty($suffix) or $this->pageTitle .= ' - ' . $suffix;
		return $this;
	}
	
	/**
	 * 重构display
	 * 
	 * @see \Think\Controller::display()
	 */
	protected function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		C('TMPL_PARSE_STRING.__DEFAULT__', __ROOT__ . '/Public/Style/' . MODULE_NAME . '/Default');
		C('TMPL_PARSE_STRING.__COMMON__', __ROOT__ . '/Public/Style/Common');
		C('TMPL_PARSE_STRING.__MDRES__', __ROOT__ . '/Public/Style/'.MODULE_NAME.'/Default');
		// layout(false);
		C('TMPL_PARSE_STRING.__TITLE__', $this->pageTitle ?  : $this->config['name']);
		/* WECHAT JSAPI 签名包 */
		if ( $this->wechatAdvance ) {
		    $signPackage = $this->wechatAdvance->getSignPackage();
		    $this->assign("wxConfig", $signPackage);
		} 
		parent::display($templateFile, $charset, $contentType, $content, $prefix);
	}
	
	/**
	 * AJAX返回正确信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return
	 *
	 */
	protected function ajaxSuccess($msg = '操作成功', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 0;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array (
				'url' => $redirectUrl,
				'delay' => $redirectDelay * 1000 
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * AJAX返回错误信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return \Utuo\BackgroundController
	 */
	protected function ajaxError($msg = '操作失败', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 1;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array (
				'url' => $redirectUrl,
				'delay' => $redirectDelay * 1000 
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * 获得当前页码
	 *
	 * @return int
	 */
	protected function getPage() {
		return I('p', 1, 'intval');
	}
	
	/**
	 * 获取分页大小
	 *
	 * @return number
	 */
	protected function getPageSize() {
		$this->pageSize = I('pageSize', 10, 'intval');
		return $this->pageSize;
	}
	
	/**
	 * 获取表单选择列表
	 *
	 * @param array $options
	 * @param string $default
	 * @param string $firstOption
	 * @return string
	 */
	protected function getOption($options, $default = null, $firstOption = null) {
		empty($options) && $options = array ();
		$ret = array ();
		empty($firstOption) or $ret[] = "<option value=''>$firstOption</option>";
		foreach ($options as $k => $v) {
			$selected = !is_null($default) && $default == $k ? " selected='selected'" : '';
			$ret[] = "<option value='$k'$selected>$v</option>";
		}
		return implode("\n", $ret);
	}
	
	/**
	 * 设置模型
	 *
	 * @param string $name
	 */
	protected function setModelName($name = null) {
		$name or $name = CONTROLLER_NAME;
		$this->modelName = $name;
	}
	
	/**
	 * 设置模型控制器名
	 * 
	 * @param string $name
	 */
	protected function setModelControllerName($name = null) {
		$name or $name = CONTROLLER_NAME;
		$this->modelControllerName = $name;
	}
	
	/**
	 * 获得模型id
	 * 
	 * @param 模型名称
	 */
	protected function getModelId($modelName) {
		$modelName = $modelName ? $modelName : $this->modelName;
		return M("Model")->where("tag='%s'", $modelName)->getField("id");
	}
	
	/**
	 * 获得登录用户
	 *
	 * @return Ambigous <mixed, NULL>
	 */
	protected function getLogin() {
		$user = session("user");
		$this->uid = $user['id'];
		return $user;
	}
	
	/**
	 * 检查登录
	 */
	protected function checkLogin() {
		$logon = true;
		$this->uid or $logon = false;
		if ($logon) {
			/* 检查该用户是否在该商家已激活过 */
			$user = $this->getLogin();
			$mUserAssociation = M("UserAssociation");
			$condition = array (
					'uid' => $user["id"],
					'cid' => $this->sid 
			);
			$mUserAssociation->where($condition)->find() or $logon = false;
		}
		cookie('model', $this->modelName);
		if (!$logon) {
			if (IS_AJAX)
				$this->ajaxError("您还没有登录,请先登录.");
			else
				redirect(url('Home', 'User', 'login', "sid={$this->sid}") . "?back=" . urlencode($this->getCurrentUrl()), 0, "您还没有登录,请先登录.");
		}
		return true;
	}
	
	/**
	 * 当前地址
	 */
	protected function getCurrentUrl() {
		unset($_REQUEST[C('TOKEN_NAME')]);
		function toArray($data, $level, $path, &$result) {
			foreach ($data as $k => $v) {
				$p = $path . ($level ? "[" . $k . "]" : $k);
				if (is_array($v)) {
					toArray($v, 1 + $level, $p, $result);
				} else {
					$result[$p] = $v;
				}
			}
			return $result;
		}
		
		$soure = array ();
		$result = toArray($_REQUEST, 0, "", $soure);
		$queryString = "";
		foreach ($result as $k => $v) {
			$queryString .= $k . "=" . $v . "&";
		}
		$queryString = trim($queryString, "&");
		
		return url(null, CONTROLLER_NAME, ACTION_NAME, "") . "?" . $queryString;
	}
	
	/**
	 * 获得客户信息
	 */
	protected function getCustomer() {
		if ($this->customer) {
			return $this->customer;
		} else {
			$this->customer = M("Customer")->find($this->cid);
		}
		return $this->customer;
	}
	
	/**
	 * 验证微信浏览器
	 * 
	 * @return boolean
	 */
	protected function checkMicroMessenger() {
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if (strpos($user_agent, 'MicroMessenger') === false) {
			return false;
		}
		return true;
	}
	
	/**
	 * 通过图文消息中传递的open_id设置微信id
	 */
	private function setWechat() {
		/* 验证签名 */
		$time = I('_t', 0);
		$sign = I('_s', "");
		$openId = I('request.open_id', 0);
		if ($time and $sign and $openId) {
			if (Sign::verify(array (
					"open_id" => $openId,
					"_t" => $time 
			), $sign)) {
				$this->open_id = $openId;
				session("wechat_id", $openId);
			}
		}
		if (!$this->open_id) {
			$session_open_id = session("wechat_id") and $this->open_id = $session_open_id;
		}
		$this->assign("open_id", $this->open_id);
	}
	
	/**
	 * 调用逻辑层方法
	 * 
	 * @param unknown $modelName
	 * @param unknown $methodName
	 * @param unknown $args
	 * @return NULL
	 */
	private function invokeLogicMethod($modelName, $methodName, $args = array()) {
		$class = parse_res_name($modelName, 'Logic');
		if (class_exists($class)) {
			$class = new \ReflectionClass($class);
			$instance = $class->newInstanceArgs();
			try {
				$method = $class->getmethod($methodName);
				return $method->invoke($instance, $args);
			} catch (\Exception $e) {
			}
		}
		return null;
	}
	
	/**
	 * 获得模型配置信息
	 */
	private function getModelConfig($id) {
		$condition = array (
				'cid' => $this->sid 
		);
		$id and $condition['id'] = $id;
		$config = M($this->modelName)->where($condition)->find();
		$configArray = unserialize($config['config']);
		$config['config'] = array ();
		foreach ($configArray as $k => $v) {
			$config['config'][$v['name']] = $v['value'];
		}
		if (empty($config['config']))
			unset($config['config']);
		return $config;
	}
	
	/**
	 * 获得主题配置
	 * 
	 * @param $tid 选择的主题
	 * @return $config 当前的主题设置
	 */
	private function getThemeConfig($tid, $config) {
		$field = 'cid';
		$value = $this->sid;
		$config['owner'] === 'Partner' and $field = 'pid' and $value = $this->pid;
		$themeConfig = M("ThemeConfig")->where("$field=%d and theme=%d", $value, $tid)->getField("config");
		$themeConfig = unserialize($themeConfig);
		return $themeConfig;
	}
	public function getCurrentContentAction() {
		$condations = array (
				'is_deleted' => 0,
				'status' => 1 
		);
		$m = D(CONTROLLER_NAME);
		$lists = $m->where($condations)->page($this->getPage(), $this->getPageSize())->order('id desc')->select();
		foreach ($lists as $k => &$v) {
			$v['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
		}
		$this->ajaxReturn($lists);
	}
}